package com.witmed.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Login
import androidx.compose.material.icons.filled.SupervisedUserCircle
import androidx.compose.material.icons.filled.VerifiedUser
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.witmed.lib_common.ActivityPath
import com.witmed.lib_http.RetrofitManager
import com.witmed.user.databinding.ActivityRegisterBinding
import com.witmed.user.intent.UserIntent
import com.witmed.user.viewmodel.RegisterState
import com.witmed.user.viewmodel.RegisterViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.RequestBody
@Route(path = ActivityPath.PAGE_REGISTER)
class RegisterActivity : AppCompatActivity() {
    lateinit var db:ActivityRegisterBinding
    lateinit var vm:RegisterViewModel
    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db=ActivityRegisterBinding.inflate(layoutInflater)
        setContentView(db.root)

        //获取ViewmModel
        vm=ViewModelProvider(this).get(RegisterViewModel::class.java)

        //接收状态
        lifecycleScope.launch {
            vm.registerState.collect{
                when(it){
                    is RegisterState.RegisterSuccess->{
                        val code=it.code
                        Log.i("Activity",code.toString())
                        //ARouter.getInstance().build(ActivityPath.PAGE_LOGIN).navigation()
                        finish()
                    }
                    is RegisterState.Error->{
                        Toast.makeText(this@RegisterActivity, ""+it.msg, Toast.LENGTH_SHORT).show()
                    }
                    else->{}
                }
            }

        }

        db.com.setContent {
            MaterialTheme {
                //保存的是输入内容
                var name by remember {
                    mutableStateOf("")
                }
                var pass by remember {
                    mutableStateOf("")
                }
                var pass2 by remember {
                    mutableStateOf("")
                }

                Box(modifier = Modifier.fillMaxSize()){
                    Column {
                        Spacer(modifier = Modifier.weight(1f))
                        Column(modifier = Modifier
                            .weight(3f)
                            .fillMaxWidth(),
                            horizontalAlignment= Alignment.CenterHorizontally
                        ) {
                            Row {
                                OutlinedTextField(shape = RoundedCornerShape(20.dp),
                                    modifier = Modifier.border(1.dp, Color.Gray,shape = RoundedCornerShape(20.dp)),
                                    leadingIcon = {
                                        Icon(imageVector = Icons.Default.SupervisedUserCircle, contentDescription = "")
                                    },
                                    label = { Text(text = "用户名") },
                                    value = name, onValueChange = {//编辑框输入值改变监听
                                        name=it
                                    })
                            }
                            Spacer(modifier = Modifier.height(20.dp))
                            Row {
                                OutlinedTextField(shape = RoundedCornerShape(20.dp),
                                    modifier = Modifier.border(1.dp, Color.Gray,shape = RoundedCornerShape(20.dp)),
                                    leadingIcon = {
                                        Icon(imageVector = Icons.Default.VerifiedUser, contentDescription = "")
                                    },
                                    label = { Text(text = "密码") },
                                    visualTransformation = PasswordVisualTransformation(),//显示密文
                                    value = pass, onValueChange = {
                                        pass=it
                                    })
                            }
                            Spacer(modifier = Modifier.height(20.dp))
                            Row {
                                OutlinedTextField(shape = RoundedCornerShape(20.dp),
                                    modifier = Modifier.border(1.dp, Color.Gray,shape = RoundedCornerShape(20.dp)),
                                    leadingIcon = {
                                        Icon(imageVector = Icons.Default.VerifiedUser, contentDescription = "")
                                    },
                                    label = { Text(text = "确认密码") },
                                    visualTransformation = PasswordVisualTransformation(),//显示密文
                                    value = pass2, onValueChange = {
                                        pass2=it
                                    })
                            }
                            Spacer(modifier = Modifier.height(20.dp))
                            Button(modifier = Modifier
                                .fillMaxWidth()
                                .padding(60.dp, 0.dp),shape = RoundedCornerShape(20.dp),
                                colors = ButtonDefaults.buttonColors(containerColor= Color.Gray),
                                onClick = { //注册事件处理
                                    if(name.isEmpty()||pass.isEmpty()||pass2.isEmpty()){
                                        Toast.makeText(this@RegisterActivity, "输入不能为空", Toast.LENGTH_SHORT).show()
                                        return@Button
                                    }
                                    if(!pass.matches(Regex("[0-9A-z_]{3,9}"))){
                                        Toast.makeText(this@RegisterActivity, "需要输入字母数字下划线3-9位", Toast.LENGTH_SHORT).show()
                                        return@Button
                                    }
                                    if(!pass.equals(pass2)){
                                        Toast.makeText(this@RegisterActivity, "两次密码不一致", Toast.LENGTH_SHORT).show()
                                        return@Button
                                    }

                                    lifecycleScope.launch {
//                val map = hashMapOf("username" to name, "password" to pass)
//                val json=Gson().toJson(map)
//                val body = RequestBody.create(MediaType.parse("application/json"), json)
                                        //发送注册意图
                                        vm.registerChannel.send(UserIntent.register(name,pass))
                                    }

                                }) {
                                Icon(imageVector = Icons.Default.Login, contentDescription ="")
                                Text(text = "注册")
                            }
                            Spacer(modifier = Modifier.height(10.dp))
                            Row(horizontalArrangement= Arrangement.SpaceBetween,modifier = Modifier
                                .fillMaxWidth()
                                .padding(60.dp, 0.dp)) {
                                Text(text = "验证码注册", modifier = Modifier.clickable {
                                    ARouter.getInstance().build(ActivityPath.PAGE_REGISTERCODE).navigation()
                                })
                                Text(text = "忘记密码")
                            }
                        }
                    }
                }
            }
        }

        /*db.btnRegister.setOnClickListener {
            val name = db.etName.text.toString()
            val pass = db.etPass.text.toString()
            val pass2 = db.etPass2.text.toString()
            if(name.isEmpty()||pass.isEmpty()||pass2.isEmpty()){
                Toast.makeText(this@RegisterActivity, "输入不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(!pass.matches(Regex("[0-9A-z_]{3,9}"))){
                Toast.makeText(this@RegisterActivity, "需要输入字母数字下划线3-9位", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if(!pass.equals(pass2)){
                Toast.makeText(this@RegisterActivity, "两次密码不一致", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            lifecycleScope.launch {
//                val map = hashMapOf("username" to name, "password" to pass)
//                val json=Gson().toJson(map)
//                val body = RequestBody.create(MediaType.parse("application/json"), json)
                //发送注册意图
                vm.registerChannel.send(UserIntent.register(name,pass))
            }
        }

        db.tvCodereg.setOnClickListener {
            ARouter.getInstance().build(ActivityPath.PAGE_REGISTERCODE).navigation()
        }*/
    }
}